from flask import Blueprint, request, jsonify
from flask_jwt_extended import (
    create_access_token,
    jwt_required,
    get_jwt_identity
)
from app.models import User, Product, Order
from app.schemas import UserSchema, ProductSchema, OrderSchema
from app import db

main = Blueprint('main', __name__)

# Schema初始化
user_schema = UserSchema()
users_schema = UserSchema(many=True)
product_schema = ProductSchema()
products_schema = ProductSchema(many=True)
order_schema = OrderSchema()
orders_schema = OrderSchema(many=True)


# 新增: 根路由
@main.route('/', methods=['GET'])
def index():
    """API根路由"""
    return {
        "message": "Welcome to Flask Shop API",
        "version": "1.0"
    }


# 用户登录路由
@main.route('/auth/login', methods=['POST'])
def login():
    """用户登录接口"""
    json_data = request.get_json()
    if not json_data:
        return {"message": "No input data provided"}, 400

    username = json_data.get('username')
    password = json_data.get('password')

    user = User.query.filter_by(username=username).first()
    if not user or not user.check_password(password):
        return {"message": "Invalid username or password"}, 401

    access_token = create_access_token(identity=user.id)
    return {"access_token": access_token}, 200


# 用户相关路由
@main.route('/users', methods=['GET', 'POST'])  # 添加 GET 方法
def users():
    """
    用户注册和查询接口
    GET: 获取所有用户列表
    POST: 创建新用户
    """
    if request.method == 'GET':
        users = User.query.all()
        return jsonify(users_schema.dump(users))

    elif request.method == 'POST':
        json_data = request.get_json()
        if not json_data:
            return {"message": "No input data provided"}, 400

        try:
            data = user_schema.load(json_data)
            # 检查用户名是否已存在
            if User.query.filter_by(username=data['username']).first():
                return {"message": "Username already exists"}, 400

            # 检查邮箱是否已存在
            if User.query.filter_by(email=data['email']).first():
                return {"message": "Email already exists"}, 400

            user = User(
                username=data['username'],
                email=data['email']
            )
            user.set_password(data['password'])

            db.session.add(user)
            db.session.commit()
            return user_schema.dump(user), 201
        except Exception as e:
            return {"message": str(e)}, 400


@main.route('/users/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前登录用户信息"""
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    if not user:
        return {"message": "User not found"}, 404
    return user_schema.dump(user)


# 商品相关路由
@main.route('/products', methods=['GET', 'POST'])  # 添加 GET 方法
def products():
    """
    商品创建和查询接口
    GET: 获取所有商品列表
    POST: 创建新商品（需要认证）
    """
    if request.method == 'GET':
        products = Product.query.all()
        return jsonify(products_schema.dump(products))

    elif request.method == 'POST':
        # 只有 POST 方法需要认证
        if not jwt_required():
            return {"message": "Authentication required"}, 401

        json_data = request.get_json()
        if not json_data:
            return {"message": "No input data provided"}, 400

        try:
            data = product_schema.load(json_data)
            product = Product(**data)
            db.session.add(product)
            db.session.commit()
            return product_schema.dump(product), 201
        except Exception as e:
            return {"message": str(e)}, 400
